package com.monkey.luffer.springboot.demo.basis.kcc;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author jiahong.liu
 */
public class Request {
    private static final String COOKIE = "cgi_ck=tPbxWG-dWHt; sid=000ifFV6kgHBHEKEWjMju-UMo9kHPmRd; nts_mail_user=alanliu336699@163.com:-1:1; _ntes_nnid=7d1cb415730fdc7cf08aa7557fd10fdf,1659581374077; _ntes_nuid=7d1cb415730fdc7cf08aa7557fd10fdf; __bid_n=1847fc07e20e2211814207; FEID=v10-5ef4ff1b96accadb01a156ed2e7c2c3f2a1b6737; __xaf_fpstarttimer__=1671100505169; __xaf_thstime__=1671100505669; __xaf_fptokentimer__=1671100505834; show_notice_popup=1; recent_op=; pid=5; gm_notify=; NTES_P_UTID=GNYpsK1s2gPKpsJe1UeIOt9lFod7moqj|1686121687; NTES_SESS=EdMaR5c2IRg2VQ8mNmPvp6uFrQILck3Xd2owKTw.yll6ybvYyrnuZzca4HC0iu7Ls5.xrXWsRmHNZNSRnSme4hMF19QrWyk8sxpm2nf0khB8lCqyiah0fOD6Wjr1xMzsIAXIUVKe8gihkYrIWTElCLYe0.g_pZxzk_J8JJ60M72mIWkwxv6_65.w9wZPDpVDOjPfNTTzVrJIAFNwizCh7GVN7; S_INFO=1686121687|0|3&80##|jhlovejh0901; P_INFO=jhlovejh0901@163.com|1686121687|0|csa|00&99|gud&1686107615&xyq#not_found&null#10#0#0|&0|xyq&cbg|jhlovejh0901@163.com; csa_user_agreement=true; login_type=urs; recent_msg=%5B%5D; ne_analysis_trace_id=1686298682798; s_n_f_l_n3=898992031060feb41686298682800; _antanalysis_s_id=1686298683492; NTES_CMT_USER_INFO=554758060%7C%E6%9C%89%E6%80%81%E5%BA%A6%E7%BD%91%E5%8F%8B0x4e_I%7Chttp%3A%2F%2Fcms-bucket.nosdn.127.net%2F2018%2F08%2F13%2F078ea9f65d954410b62a52ac773875a1.jpeg%7Cfalse%7Camhsb3ZlamgwOTAxQDE2My5jb20%3D; vinfo_n_f_l_n3=898992031060feb4.1.0.1686298682800.0.1686298685593; FPTOKEN=Es7gFWTvhxcj3uh4IOl3oGrWCw5RItpcD+3ukbkGoxXozn8QODTie5b4eCwbu6oZL4mHufTt/wV0ZmwZVy7SRgj3ZblVm5+BFtJmieInhKHPPedlCYay6GqyRBLwZadaiLAOQB2ZHbMySwWEZRSEJXzy9hHMRSEPJK8eIlURDlbM/O5W0jf/vgQM4rUiiv+vmxqmMau56Tx2R2Z6tmQn45h6M0oqWQCiz9XBa614mIQXYhUgqJZuFwAyGTrjtFsa+lF/fY8d2IFKi7WzJgMfRMaH/kqfJtKSMoqpHDmG6oTvYgthiX62w0uU3Gn7AH1cD48FGNmQEFi00HuK/HHlrM9240LWlM9GtKr3uFgh9wAHBnibgYdUnxr3GJBgg7Q1jjTkX0dngD4rrMJhpd9XJA==|hKhRH/HtHYTBO7rgzfJsIGI6s+R1aJE7Uoki7cOUzk0=|10|77317e16ec110534e9f2d7f8b7cdbf4b; _nietop_foot=%u68A6%u5E7B%u897F%u6E38%u7535%u8111%u7248%7Cxyq.163.com; unisdk_udid=f776b3ec1a2c75af3e3602a8f1028956; timing_user_id=time_yWI4s3nArE; login_urs=; login_id=; reply_que=; new_msg=; topbarnewsshow=1; reset_urs=0";
    private static final String URL = "https://xyq.gm.163.com/cgi-bin/csa/csa_sprite.py?act=ask&question={}&product_name=xyq";
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String input = scanner.nextLine();
            if ("end".equalsIgnoreCase(input)) {
                break;
            }
            if (StringUtils.isBlank(input)) {
                System.out.println("输入为空");
                continue;
            }
            ask(URL.replace("{}", input));
        }
        scanner.close();
    }

    private static void ask(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response;
        BasicCookieStore cookieStore = new BasicCookieStore();
        setCookie(cookieStore);
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCookieStore(cookieStore)
                .build();
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                handleContent(content);
            }
        } catch (Exception e) {


            System.out.println(e.getMessage());
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }

    private static void setCookie(BasicCookieStore cookieStore) {
        String[] cookieArr = COOKIE.split(";");
        for (String item : cookieArr) {
            item = item.trim();
            String[] itemArr = item.split("=");
            if (itemArr.length < 2) {
                continue;
            }
            String key = itemArr[0];
            String value = itemArr[1];
            BasicClientCookie clientCookie = new BasicClientCookie(key, value);
            cookieStore.addCookie(clientCookie);
        }
    }

    private static void handleContent (String content) {
        if (StringUtils.isBlank(content)) {
            System.out.println("输入为空");
            return;
        }

        StringBuilder sb = new StringBuilder();
        int i = -1;
        int pos = 0;

        while ((i = content.indexOf("\\u", pos)) != -1) {
            sb.append(content.substring(pos, i));
            if (i + 5 < content.length()) {
                pos = i + 6;
                sb.append((char) Integer.parseInt(content.substring(i + 2, i + 6), 16));
            }
        }
        //如果pos位置后，有非中文字符，直接添加
        sb.append(content.substring(pos));
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        String value = jsonObject.getString("answer");
        content = Html2Text.getContent(value);
        for (String item: content.split("　")) {
            System.out.println(item);
        }

    }


    static class Html2Text extends HTMLEditorKit.ParserCallback {

        private static Html2Text html2Text = new Html2Text();

        StringBuffer s;

        public Html2Text() {
        }

        public void parse(String str) throws IOException {

            InputStream iin = new ByteArrayInputStream(str.getBytes());
            Reader in = new InputStreamReader(iin);
            s = new StringBuffer();
            ParserDelegator delegator = new ParserDelegator();
            // the third parameter is TRUE to ignore charset directive
            delegator.parse(in, this, Boolean.TRUE);
            iin.close();
            in.close();
        }

        @Override
        public void handleText(char[] text, int pos) {
            s.append(text);
        }

        public String getText() {
            return s.toString();
        }

        public static String getContent(String str) {
            try {
                html2Text.parse(str);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return html2Text.getText();
        }
    }
}
